package sport

import (
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/middleware"
	"github.com/bgmp/model"
	"github.com/bgmp/service"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func (b Base) GetEnergy(c *gin.Context, req *GetEnergyRequest) *GetEnergyResponse {

	go func(heartRate []int) {
		heart := model.Heart{
			UserId:   middleware.GetUserId(c),
			Heart:    heartRate[len(heartRate)-1],
			TimeDate: time.Now(),
		}
		_ = heart.Create(config.DB)
	}(req.HeartRate)

	err, resp := service.SportPredict(req.HeartRate)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}

	f, err := strconv.ParseFloat(resp.Energy, 64)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}

	exercise := model.Exercise{
		UserId:   middleware.GetUserId(c),
		Calorie:  f * 5 / 12,
		CreateAt: time.Now(),
	}
	_ = exercise.Save(config.DB)

	return &GetEnergyResponse{
		Energy: f,
	}
}

type GetEnergyRequest struct {
	HeartRate []int `json:"heart_rate"`
}

type GetEnergyResponse struct {
	Energy float64 `json:"energy"`
}
